package com.example.demo.server.controller;

import com.example.demo.server.common.CommonResponse;
import com.example.demo.server.common.SessionUtils;
import com.example.demo.server.common.UserUtils;
import com.example.demo.server.model.UserInfo;
import com.example.demo.server.service.UserService;


public class UserController {

    private UserService userService = new UserService();

    // 由于我们模拟实现的网站没有伪造请求的可能，再次校验的步骤省略
    public CommonResponse register(UserInfo userInfo) {
        String username = UserUtils.getUsername();
        userInfo.setUsername(username);
        userInfo.setPassword(UserUtils.encrypt(userInfo.getPassword()));
        int rows = userService.register(userInfo);
        return rows == 1 ? CommonResponse.success(1, username) : CommonResponse.fail(-1, "SQL Exception!");
    }

    // 登录接口
    public CommonResponse login(UserInfo userInfo) {
        // 根据用户名查询对象
        UserInfo user = userService.getUserByUsername(userInfo.getUsername());
        if(user == null || user.getId() == 0) {
            return CommonResponse.fail(-2, "用户名或者密码错误！");
        }
        // 验证密码（左边待测，右边数据库查出来的）
        if(!UserUtils.confirm(userInfo.getPassword(), user.getPassword())) {
            return CommonResponse.fail(-2, "用户名或者密码错误！");
        }
        // 保存会话
        SessionUtils.setUser(user);
        return CommonResponse.success("Login Success！");
    }


}
